package com.wrupple.muba.catalogs.client.module.services.presentation.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.domain.FilterData;
import com.wrupple.muba.common.shared.State.StorageManager;
import com.wrupple.muba.common.shared.StateTransition;

public class LoadEntireResultSetCallback<T extends JavaScriptObject> extends DataCallback<List<T>> {
	
	
	private String catalog;
	private FilterData filter;
	private List<T> acumulator;
	private int increment;
	private StateTransition<List<T>> callback;
	private StorageManager delegate;
	
	

	public LoadEntireResultSetCallback(String catalog, FilterData filter,int increment,StorageManager delegate, StateTransition<List<T>> callback) {
		super();
		this.catalog = catalog;
		this.filter = filter;
		this.acumulator = new ArrayList<T>();
		this.increment = increment;
		this.callback = callback;
		this.delegate = delegate;
		filter.setStart(0);
		filter.setEnd(increment);
	}

	@Override
	public void execute() {
		if(result==null||result.isEmpty()){
			//we are finished
			callback.setResult(acumulator);
			callback.execute();
		}else{
			acumulator.addAll(result);
			filter.setStart(acumulator.size());
			filter.setEnd(acumulator.size()+increment);
			start();
		}
	}
	
	public void start(){
		StateTransition transition = this;
		delegate.read(catalog, filter, transition );
	}

}
